package com.liveinstars.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.liveinstars.common.StrUtil;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Comparator;

/**
 * Created by guoyanjiang on 2018-12-06.
 */
public class ComparatorUtil {
    public static Comparator<Object> getSortComparator(String orderField, String orderType) {
        return getComparator(orderField, orderType, (obj, innerOrderField) -> getAFieldValue(obj, innerOrderField));
    }

    public static Comparator<Object> getRankSortComparator(String orderField, String orderType) {
        return getComparator(orderField, orderType, (obj, innerOrderField) -> getaRankFieldValue(obj, innerOrderField));
    }

    public static Comparator<Object> getComparator(String orderfield, String ordertype, ValueTemplate template) {
        return (a, b) -> {
            int num = 0;
            try {
                if (!StringUtils.isEmpty(orderfield)) {
                    Object aValue = ((JSONObject) a).getString(orderfield);
                    Object bValue = ((JSONObject) b).getString(orderfield);
                    if (aValue == bValue) {
                        return 0;
                    } else if (aValue == null) {
                        return 1;
                    } else if (bValue == null) {
                        return -1;
                    }
                    if ("asc".equals(ordertype)) {
                        num = template.getValue((JSONObject) a,orderfield).compareTo(template.getValue((JSONObject) b, orderfield));
                    } else {
                        num = template.getValue((JSONObject) b, orderfield).compareTo(template.getValue((JSONObject) a, orderfield));
                    }
                } else {
                    num = 1;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                return num;
            }
        };
    }

    public interface ValueTemplate{
        Comparable getValue(JSONObject obj, String orderField);
    }

    private static Integer getAFieldValue(JSONObject obj, String orderField) {
        return Integer.parseInt(StrUtil.escapeExprSpecialWord(obj.getString(orderField)));
    }

    private static BigDecimal getaRankFieldValue(JSONObject obj, String orderField) {
        //特殊字段处理，还要考虑空值
        if ("turnover".equals(orderField) || "total".equals(orderField) || "volume".equals(orderField)) {

            return new BigDecimal(StrUtil.escapeExprSpecialWord(((JSONObject) obj).getString(orderField)));
        }
        return obj.getBigDecimal(orderField);
    }
}
